package it.polimi.managers;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class BaseManagerIml implements BaseManager {

	@PersistenceContext(unitName = "ps_persistence_ctx")
	protected EntityManager em;

	@Override
	public void create(Object entity) {
		if (entity == null) {
			throw new NullPointerException("trying to persist null entity object");
		}

		em.persist(entity);
	}

	@Override
	public void delete(Object entity) {
		if (entity == null) {
			throw new NullPointerException("trying to delete null entity object");
		}

		em.remove(em.merge(entity));
	}

	@Override
	public <T> T merge(T entity) {

		return em.merge(entity);

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
	public <T> T mergeInNewTransaction(T t) {
		return em.merge(t);

	}

	@Override
	public <T> T findById(Class<T> clazz, Object id) {
		if (id == null) {
			return null;
		}

		return em.find(clazz, id);
	}

}
